<template>
  <div>
    <page-loading
      :loading.sync="pageLoading"
      :error.sync="pageError"
      :enable-pull-refresh="false"
      @reload="getDetail"
    >
      <template v-if="hasInfo">
        <video-player
          class="vp"
          :url="videoPlayUrl"
          :poster="videoInfo.pic"
          :duration="videoInfo.duration"
        />
        <van-tabs
          ref="vanTabs"
          class="tabs"
          v-model="activeTab"
          :title-active-color="rootThemeColor"
          animated
          @change="onTabChange"
        >
          <van-tab title="简介">
            <video-info
              :info="videoInfo"
              :tags="videoTags"
            />
            <video-toolbar
              :fav-checked="favStatus"
              :share-pic="videoInfo.pic"
              :share-title="videoInfo.title"
              @fav-click="onFavClick"
            />
            <video-part
              v-if="hasParts"
              :parts="videoInfo.pages"
              :current-part.sync="videoInfo.cid"
              @select="onSelectPart"
            />
            <video-related
              :videos="relatedVideos"
            />
          </van-tab>
          <van-tab>
            <template #title>评论 {{ videoInfo.stat.reply | formatNumber }}</template>
            <video-comment
              :comments="videoComments"
              popup-class="bpopup"
            />
          </van-tab>
        </van-tabs>
      </template>
    </page-loading>
  </div>
</template>

<script>
import PageLoading from '@/components/page-loading/PageLoading'
import VideoPlayer from '@/components/video-player/VideoPlayer'
import VideoInfo from '@/components/video/VideoInfo'
import VideoToolbar from '@/components/video/VideoToolbar'
import VideoPart from '@/components/video/VideoPart'
import VideoRelated from '@/components/video/VideoRelated'
import VideoComment from '@/components/comment/Comment'
import { apiGetDetail, apiGetPlayUrl, apiGetVideoTags, apiGetVideoRelated, apiGetVideoComment } from '@/api/video.js'
import { getStorage, setStorage } from '@/utils/localStorage'
import { formatNumber } from '@/filters/filters'
import pageLoadingMixin from '@/mixins/pageLoading'
import { Tabs as VanTabs, Tab as VanTab } from 'vant'
export default {
  name: 'Video',
  inject: ['rootThemeColor', 'routerConfig', 'rootTitle', 'rootKeyword'],
  mixins: [pageLoadingMixin],
  metaInfo () {
    return {
      title: this.title,
      meta: [
        { vmid: 'keywords', name: 'keywords', content: this.keywords },
        { vmid: 'description', name: 'description', content: this.description }
      ]
    }
  },
  components: {
    PageLoading,
    VideoPlayer,
    VanTabs,
    VanTab,
    VideoInfo,
    VideoToolbar,
    VideoPart,
    VideoRelated,
    VideoComment
  },
  props: {
    // 视频bvid
    bvid: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      videoId: this.bvid,
      videoInfo: null,
      videoPlayUrl: null,
      videoTags: [],
      relatedVideos: [],
      videoComments: [],
      activeTab: 0,
      favStatus: false
    }
  },
  computed: {
    title () {
      let word = this.rootTitle
      if (this.hasInfo) {
        word = `${this.videoInfo.title}_${word}`
      }
      return word
    },
    keywords () {
      let word = this.rootKeyword
      if (this.hasInfo) {
        word = `${this.videoInfo.title},${this.breadcrumb.name},${this.breadcrumb.subName},${word}`
      }
      return word
    },
    description () {
      let word = ''
      if (this.hasInfo) {
        word = (this.videoInfo.desc || '').replace(/\n/g, '').substring(0, 200) || this.videoInfo.title
      }
      return word
    },
    hasInfo () {
      return this.videoInfo !== null
    },
    hasParts () {
      return this.hasInfo && this.videoInfo.pages.length > 1
    },
    breadcrumb () {
      const result = {}
      for (const config of this.routerConfig) {
        const { name, tid, sub, hide } = config
        if (sub) {
          let match = false
          for (const subConfig of sub) {
            const subTid = subConfig.tid
            if (this.videoInfo.tid === subTid) {
              match = true
              result.name = name
              result.tid = tid
              result.hide = hide
              result.subName = subConfig.name
              result.subTid = subConfig.tid
              result.subHide = subConfig.hide
              break
            }
          }
          if (match) {
            break
          }
        }
      }
      return result
    }
  },
  filters: {
    formatNumber
  },
  created () {
    this.getDetail()
  },
  watch: {
    bvid (newVal) {
      this.videoId = newVal
    },
    videoId (newVal) {
      this.pageError = false
      this.videoComments = []
      this.getDetail()
    }
  },
  methods: {
    // 获取视频基本信息和播放地址
    getDetail () {
      apiGetDetail({
        bvid: this.videoId
      }).then(res => {
        const { code, data } = res
        if (code === 0 && data !== null) {
          this.videoInfo = data
          this.initFav()
        } else {
          this.pageError = true
        }
        return data
      }).then(result => {
        if (typeof result.redirect_url !== 'undefined') {
          const id = result.redirect_url.substring(result.redirect_url.lastIndexOf('/') + 1)
          this.$router.push({ name: 'bangumi', params: { id } })
        } else {
          const { aid, bvid, cid } = result
          this.getRelatedVideo(aid, bvid)
          this.getVideoPlayUrl(aid, bvid, cid)
          this.getVideoTags(aid, bvid)
        }
      }).catch(() => {
        this.$router.replace({ name: '404' })
        // this.pageError = true
      }).finally(() => {
        this.pageLoading = false
      })
    },
    // 获取视频播放地址
    getVideoPlayUrl (aid, bvid, cid) {
      apiGetPlayUrl({
        cid,
        aid,
        bvid
      }).then(res => {
        const { code, data } = res
        if (code === 0 && data !== null) {
          const { durl } = data
          this.videoPlayUrl = durl[0].url
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // 获取视频标签
    getVideoTags (aid, bvid) {
      apiGetVideoTags({
        aid,
        bvid
      }).then(res => {
        const { code, data } = res
        if (code === 0 && data !== null) {
          this.videoTags = data
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // 获取和此视频类似的其他视频
    getRelatedVideo (aid, bvid) {
      apiGetVideoRelated({
        aid,
        bvid
      }).then(res => {
        const { code, data } = res
        if (code === 0 && data !== null) {
          this.relatedVideos = data.slice(0, 30)
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // 获取视频的评论
    getVideoComment (aid, bvid) {
      apiGetVideoComment({
        aid,
        bvid
      }).then(res => {
        const { code, data } = res
        if (code === 0 && data !== null) {
          const { replies } = data
          this.videoComments = replies
        }
      }).catch(err => {
        console.log(err)
      })
    },
    onTabChange (name) {
      if (name === 1 && !this.videoComments.length) {
        // 评论标签首次加载
        const { aid, bvid } = this.videoInfo
        this.getVideoComment(aid, bvid)
      }
    },
    // 存储设置缓存
    setHistory ({ type, data, action = 'add' } = {}) {
      const vals = getStorage(type)
      const matchIndex = vals.findIndex(val => val.bvid === data.bvid)
      if (matchIndex === -1) {
        const { aid, bvid, pic, owner: { name }, title } = data
        const item = {
          aid,
          bvid,
          pic,
          owner: name,
          title,
          isHistory: 1,
          timestamp: new Date().getTime()
        }
        vals.unshift(item)
        setStorage(type, vals)
      } else {
        if (action === 'del') {
          vals.splice(matchIndex, 1)
          setStorage(type, vals)
        }
      }
    },
    initFav () {
      const favs = getStorage('fav_history')
      const matchIndex = favs.findIndex(fav => fav.bvid === this.videoInfo.bvid)
      this.favStatus = matchIndex > -1
    },
    onFavClick () {
      this.favStatus = !this.favStatus
      this.setHistory({
        type: 'fav_history',
        data: this.videoInfo,
        action: !this.favStatus ? 'del' : ''
      })
    },
    onSelectPart (part) {
      this.getVideoPlayUrl(this.videoInfo.aid, this.videoInfo.bvid, part.cid)
    }
  }
}
</script>
<style lang="scss" scoped>
  @media screen and (orientation:portrait) {
    // 竖屏
    .tabs ::v-deep .van-tabs__wrap {
      position: sticky;
      top: 255px;
      z-index: 2;
    }
    .vp{
      position: sticky;
      top: 44px;
      z-index: 2;
    }
  }
</style>
